#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project ：api_automation_test 
@File    ：dingding_push.py
@IDE     ：PyCharm 
@Author  ：XiaoDengYa
@Date    ：2021/7/22/022 16:21 
"""

import base64
import hashlib
import hmac
import json
import time
import urllib.parse
import urllib.request

import requests

from common.tools.read_file import ReadFile


class SendMessage(object):
    def __init__(self):
        self.read = ReadFile()
        self.secret = self.read.read_config("$.dingding.secret")
        self.token = self.read.read_config("$.dingding.token")
        self.timestamp = str(round(time.time() * 1000))
        self.session = requests.session()

    def get_sign(self):
        try:
            secret_enc = self.secret.encode('utf-8')
            string_to_sign = '{}\n{}'.format(self.timestamp, self.secret)
            string_to_sign_enc = string_to_sign.encode('utf-8')
            hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
            sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))
            return sign
        except Exception as e:
            print("sign生成失败，错误原因：{}".format(e))

    def send_request(self, data):
        url = f"https://oapi.dingtalk.com/robot/send?access_token={self.token}&sign={self.get_sign()}&timestamp={self.timestamp}"
        header = {
            "Content-Type": "application/json",
            "Charset": "UTF-8"
        }
        try:
            re = self.session.post(url=url, headers=header, data=json.dumps(data))
            print(re.json())
        except Exception as e:
            print("发送钉钉信息失败：{}".format(e))

    def run_send(self, title, isAtALL=False, msg=None):
        my_data = {
            "msgtype": "markdown",
            "markdown": {
                "title": title,
                "text": f"测试未通过，具体原因：{msg}",
            },
            "at": {
                "atMobiles": ["18574866512"],
                "isAtALL": isAtALL
            }
        }
        return self.send_request(my_data)
